#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>


void* handle_client(void* args) 
{
    int clientfd = *(int*)args;
    free(args); // 释放内存

    pthread_detach(pthread_self());

    char buffer[128] = {0};
    while (1) {
        int cnt = recv(clientfd, buffer, 128, 0);
        if (cnt == 0) {
            break;
        }
        buffer[cnt] = 0;
        
        printf("clientfd: %d, count: %d, message: %s\n", clientfd, cnt, buffer);
    }

    close(clientfd);
    return NULL;
}


int main()
{

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket error");
        return -1;
    }

    int opt = 1;
    int n = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    if (n < 0) {
        perror("setsockopt error");
        close(sockfd);
        return -2;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    // addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    addr.sin_port = htons(8080);

    n = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if (n < 0) {
        perror("bind error");
        close(sockfd);
        return -3;
    }

    n = listen(sockfd, 8);
    if (n < 0) {
        perror("listen error");
        close(sockfd);
        return -4;
    }

    while (1) {
        
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);

        int* clientfd = (int*)malloc(sizeof(int));
        *clientfd = accept(sockfd, (struct sockaddr*)&peer, &len);
       
        if (*clientfd < 0) {
            perror("accept error");
            continue;
        }
        
        pthread_t thread;
        pthread_create(&thread, NULL, handle_client, clientfd);
        // handle_client 中进行线程分离，无需 join
    }

    close(sockfd);

    return 0;
}